/*
* 日常指标
* */

import 'package:center_beijing/api/product_api.dart';
import 'package:center_beijing/api/statistical_analysis_api.dart';
import 'package:center_beijing/common/logutil.dart';
import 'package:center_beijing/common/styles.dart';
import 'package:center_beijing/common/utils.dart';
import 'package:center_beijing/config/global_config.dart';
import 'package:center_beijing/models/selectItem.dart';
import 'package:center_beijing/widgets/custom_loading_widget.dart';
import 'package:center_beijing/widgets/custom_radio.dart';
import 'package:center_beijing/widgets/pull_select_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter_echarts/flutter_echarts.dart';
import 'package:flutter_pickers/pickers.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'dart:async';
import 'dart:convert';

class DailyIndicators extends StatefulWidget {
  @override
  _DailyIndicatorsState createState() => _DailyIndicatorsState();
}

class _DailyIndicatorsState extends State<DailyIndicators> with SingleTickerProviderStateMixin {

  CustomLoading loading = CustomLoading.withMessage('请稍候...');
  List<SelectItems> projectNameList = [SelectItems(label: '全部项目', value: '-1')];
  SelectItems selectProject = SelectItems(label: '全部项目', value: '-1');
  final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
  List<Map<String, Object>> _data1 = [
    {'name': 'Please wait', 'value': 0}
  ];
  List navTitle = ['日常指标', '订单进度', '任务进度', '堆场库存', '运输进度'];
  int currentStatus = 0;

  bool chartLoading = true;
  bool flag = false;
  String currentIndexStr = '日常指标';

  var cardInfo = Map();//卡片信息
  var charts = [];
  var currentDate = '';
  String selectType ='1';//1方量  2数量

  @override
  void didChangeDependencies() {
    // TODO: implement didChangeDependencies
    super.didChangeDependencies();
    print('didChangeDependencies');
  }
  @override
  void initState() {

    super.initState();
    this.getOrders();
    this.getInfo();
    print('initState');
  }

  @override
  void dispose() {
    super.dispose();
  }

  getInfo() async {
    var pass = {
      'projectId': GlobalConfig.selectFactory.value,
      'orderId': selectProject.value,
      'start': currentDate==''?Utils.timeUtil(DateTime.now().toIso8601String()):currentDate,
      'end': currentStatus==1?currentDate:Utils.timeUtil(DateTime.now().toIso8601String()),
    };
    var result = await getAnalysisData(pass);
    if (result != null) {
      this.setState(() {
        cardInfo = result['card'];
        charts = result['chart'];
      });
    }
  }

  /*
  * 获取订单列表
  * */
  getOrders() async {
    var pass = {'projectId': GlobalConfig.selectFactory.value};
    var result = await getOrderList(pass);
    loading.dismiss();
    if (result != null) {
      List<SelectItems> tem = [SelectItems(label: '全部项目', value: '-1')];
      result.forEach((item) {
        tem.add(SelectItems(
            label: item['orderName'], value: item['id'], dict: item));
      });
      this.setState(() {
        projectNameList = tem;
      });
    }
  }

  getNavItem(item) {
    return GestureDetector(
      onTap: () {
        this.setState(() {
          flag = false;
          currentIndexStr = item;
        });
      },
      child: Container(
        padding: EdgeInsets.fromLTRB(
            Styles.spacing8, Styles.spacing4, Styles.spacing8, Styles.spacing4),
        margin: EdgeInsets.fromLTRB(0, Styles.spacing4, 0, Styles.spacing4),
        decoration: BoxDecoration(
            border: Border.all(
                color: currentIndexStr == item
                    ? Styles.BlueColor
                    : Colors.transparent),
            color:
            currentIndexStr == item ? Styles.BlueColor3 : Styles.GrayLight),
        child: Text(
          item,
          style: TextStyle(
              color: currentIndexStr == item
                  ? Styles.BlueColor
                  : Styles.TitleItemColor,
              fontSize: Styles.NormalFont),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: SingleChildScrollView(
        child: Column(
          children: [
            Container(
              color: Colors.white,
              padding: EdgeInsets.fromLTRB(Styles.spacing8, Styles.spacing8,
                  Styles.spacing8, Styles.spacing8),
              child: Row(
                children: [
                  Expanded(
                      child: GestureDetector(
                        onTap: () {
                          this.setState(() {
                            currentStatus = 0;
                            currentDate = Utils.timeUtil(DateTime.now().toIso8601String());
                            this.getInfo();
                          });
                        },
                        child: Container(
                          decoration: BoxDecoration(
                              color: currentStatus == 0
                                  ? Styles.BlueColor
                                  : Colors.white,
                              borderRadius:
                              BorderRadius.all(Radius.circular(12.0.r))),
                          padding: EdgeInsets.fromLTRB(
                              0, Styles.spacing4, 0, Styles.spacing4),
                          margin: EdgeInsets.fromLTRB(
                              Styles.spacing4, 0, Styles.spacing4, 0),
                          alignment: Alignment.center,
                          child: Text(
                            '今日',
                            style: TextStyle(
                                color: currentStatus == 0
                                    ? Colors.white
                                    : Styles.DetailColor,
                                fontSize: Styles.NormalFont),
                          ),
                        ),
                      )),
                  Expanded(
                      child: GestureDetector(
                        onTap: () {
                          this.setState(() {
                            currentStatus = 1;
                            currentDate = Utils.timeUtil(DateTime.now().subtract(Duration(days:1)).toIso8601String());
                            this.getInfo();
                          });
                        },
                        child: Container(
                          decoration: BoxDecoration(
                              color: currentStatus == 1
                                  ? Styles.BlueColor
                                  : Colors.white,
                              borderRadius:
                              BorderRadius.all(Radius.circular(12.0.r))),
                          padding: EdgeInsets.fromLTRB(
                              0, Styles.spacing4, 0, Styles.spacing4),
                          margin: EdgeInsets.fromLTRB(
                              Styles.spacing4, 0, Styles.spacing4, 0),
                          alignment: Alignment.center,
                          child: Text(
                            '昨日',
                            style: TextStyle(
                                color: currentStatus == 1
                                    ? Colors.white
                                    : Styles.DetailColor,
                                fontSize: Styles.NormalFont),
                          ),
                        ),
                      )),
                  Expanded(
                      child: GestureDetector(
                        onTap: () {
                          this.setState(() {
                            currentStatus = 2;
                            currentDate = Utils.timeUtil(DateTime.now().subtract(Duration(days:6)).toIso8601String());
                            this.getInfo();
                          });
                        },
                        child: Container(
                          decoration: BoxDecoration(
                              color: currentStatus == 2
                                  ? Styles.BlueColor
                                  : Colors.white,
                              borderRadius:
                              BorderRadius.all(Radius.circular(12.0.r))),
                          padding: EdgeInsets.fromLTRB(
                              0, Styles.spacing4, 0, Styles.spacing4),
                          margin: EdgeInsets.fromLTRB(
                              Styles.spacing4, 0, Styles.spacing4, 0),
                          alignment: Alignment.center,
                          child: Text(
                            '近七日',
                            style: TextStyle(
                                color: currentStatus == 2
                                    ? Colors.white
                                    : Styles.DetailColor,
                                fontSize: Styles.NormalFont),
                          ),
                        ),
                      )),
                  Expanded(
                      child: GestureDetector(
                        onTap: () {
                          this.setState(() {
                            currentStatus = 3;
                            currentDate = Utils.timeUtil(DateTime.now().subtract(Duration(days:29)).toIso8601String());
                            this.getInfo();
                          });
                        },
                        child: Container(
                          decoration: BoxDecoration(
                              color: currentStatus == 3
                                  ? Styles.BlueColor
                                  : Colors.white,
                              borderRadius:
                              BorderRadius.all(Radius.circular(12.0.r))),
                          padding: EdgeInsets.fromLTRB(
                              0, Styles.spacing4, 0, Styles.spacing4),
                          margin: EdgeInsets.fromLTRB(
                              Styles.spacing4, 0, Styles.spacing4, 0),
                          alignment: Alignment.center,
                          child: Text(
                            '近30日',
                            style: TextStyle(
                                color: currentStatus == 3
                                    ? Colors.white
                                    : Styles.DetailColor,
                                fontSize: Styles.NormalFont),
                          ),
                        ),
                      )),
                ],
              ),
            ),
            PullSelectWidget(
              items: projectNameList,
              text_align: TextAlign.center,
              rightText:selectProject.label,
              selectCallback: (value) {
                this.selectProject = value;
                this.getInfo();
              },
            ),
            Container(
              margin: EdgeInsets.fromLTRB(
                  0, Styles.spacing8, 0, Styles.spacing8),
              child: Row(
                children: [
                  Expanded(
                      child: Container(
                        decoration: BoxDecoration(
                            // gradient: LinearGradient(
                            //   //渐变位置
                            //     begin: Alignment.topCenter,
                            //     end: Alignment.bottomCenter,
                            //     stops: [
                            //       0.0,
                            //       1.0
                            //     ], //[渐变起始点, 渐变结束点]
                            //     //渐变颜色[始点颜色, 结束颜色]
                            //     colors: [
                            //       Color.fromRGBO(125, 216, 151, 1),
                            //       Color.fromRGBO(74, 208, 181, 1)
                            //     ]),
                            color: Color.fromRGBO(84, 112, 198, 1),
                            borderRadius:
                            BorderRadius.all(Radius.circular(8.0.r))),
                        padding: EdgeInsets.fromLTRB(
                            0, Styles.spacing16, 0, Styles.spacing16),
                        margin: EdgeInsets.fromLTRB(
                            Styles.spacing8, 0, Styles.spacing8, 0),
                        child: Column(
                          children: [
                            Container(
                              child: Text(
                                '完成量',
                                style: TextStyle(
                                    color: Styles.ShareWhite,
                                    fontSize: Styles.NormalFont),
                              ),
                            ),
                            Container(
                              margin: EdgeInsets.only(top: Styles.spacing16),
                              padding: EdgeInsets.fromLTRB(
                                  0, Styles.spacing8, 0, Styles.spacing8),
                              child: Text(
                                '${cardInfo['successVolume']}m³',
                                style: TextStyle(
                                    color: Styles.ShareWhite,
                                    fontSize: Styles.MiddleFont17),
                              ),
                            ),
                            Container(
                              padding: EdgeInsets.fromLTRB(0, 0, 0, 0),
                              child: Text(
                                '${cardInfo['successQuantity']}片',
                                style: TextStyle(
                                    color: Styles.ShareWhite,
                                    fontSize: Styles.NormalFont),
                              ),
                            ),
                          ],
                        ),
                      )),
                  Expanded(
                      child: Container(
                        decoration: BoxDecoration(
                            // gradient: LinearGradient(
                            //   //渐变位置
                            //     begin: Alignment.topCenter,
                            //     end: Alignment.bottomCenter,
                            //     stops: [
                            //       0.0,
                            //       1.0
                            //     ], //[渐变起始点, 渐变结束点]
                            //     //渐变颜色[始点颜色, 结束颜色]
                            //     colors: [
                            //       Color.fromRGBO(112, 209, 250, 1),
                            //       Color.fromRGBO(86, 175, 239, 1)
                            //     ]),
                            color: Color.fromRGBO(145, 204, 117, 1),
                            borderRadius:
                            BorderRadius.all(Radius.circular(8.0.r))),
                        padding: EdgeInsets.fromLTRB(
                            0, Styles.spacing16, 0, Styles.spacing16),
                        margin: EdgeInsets.fromLTRB(
                            Styles.spacing8, 0, Styles.spacing8, 0),
                        child: Column(
                          children: [
                            Container(
                              child: Text(
                                '入库量',
                                style: TextStyle(
                                    color: Styles.ShareWhite,
                                    fontSize: Styles.NormalFont),
                              ),
                            ),
                            Container(
                              margin: EdgeInsets.only(top: Styles.spacing16),
                              padding: EdgeInsets.fromLTRB(
                                  0, Styles.spacing8, 0, Styles.spacing8),
                              child: Text(
                                '${cardInfo['warehouseVolume']}m³',
                                style: TextStyle(
                                    color: Styles.ShareWhite,
                                    fontSize: Styles.MiddleFont17),
                              ),
                            ),
                            Container(
                              padding: EdgeInsets.fromLTRB(0, 0, 0, 0),
                              child: Text(
                                '${cardInfo['warehouseQuantity']}片',
                                style: TextStyle(
                                    color: Styles.ShareWhite,
                                    fontSize: Styles.NormalFont),
                              ),
                            ),
                          ],
                        ),
                      )),
                ],
              ),
            ),
            Container(
              margin: EdgeInsets.fromLTRB(
                  0, Styles.spacing8, 0, Styles.spacing8),
              child: Row(
                children: [
                  Expanded(
                      child: Container(
                        decoration: BoxDecoration(
                            // gradient: LinearGradient(
                            //   //渐变位置
                            //     begin: Alignment.topCenter,
                            //     end: Alignment.bottomCenter,
                            //     stops: [
                            //       0.0,
                            //       1.0
                            //     ], //[渐变起始点, 渐变结束点]
                            //     //渐变颜色[始点颜色, 结束颜色]
                            //     colors: [
                            //       Color.fromRGBO(198, 163, 253, 1),
                            //       Color.fromRGBO(138, 112, 252, 1)
                            //     ]),
                            color: Color.fromRGBO(250, 200, 88, 1),
                            borderRadius:
                            BorderRadius.all(Radius.circular(8.0.r))),
                        padding: EdgeInsets.fromLTRB(
                            0, Styles.spacing16, 0, Styles.spacing16),
                        margin: EdgeInsets.fromLTRB(
                            Styles.spacing8, 0, Styles.spacing8, 0),
                        child: Column(
                          children: [
                            Container(
                              child: Text(
                                '发货量',
                                style: TextStyle(
                                    color: Styles.ShareWhite,
                                    fontSize: Styles.NormalFont),
                              ),
                            ),
                            Container(
                              margin: EdgeInsets.only(top: Styles.spacing16),
                              padding: EdgeInsets.fromLTRB(
                                  0, Styles.spacing8, 0, Styles.spacing8),
                              child: Text(
                                '${cardInfo['transportVolume']}m³',
                                style: TextStyle(
                                    color: Styles.ShareWhite,
                                    fontSize: Styles.MiddleFont17),
                              ),
                            ),
                            Container(
                              padding: EdgeInsets.fromLTRB(0, 0, 0, 0),
                              child: Text(
                                '${cardInfo['transportQuantity']}片',
                                style: TextStyle(
                                    color: Styles.ShareWhite,
                                    fontSize: Styles.NormalFont),
                              ),
                            ),
                          ],
                        ),
                      )),
                  Expanded(
                      child: Container(
                        decoration: BoxDecoration(
                            // gradient: LinearGradient(
                            //   //渐变位置
                            //     begin: Alignment.topCenter,
                            //     end: Alignment.bottomCenter,
                            //     stops: [
                            //       0.0,
                            //       1.0
                            //     ], //[渐变起始点, 渐变结束点]
                            //     //渐变颜色[始点颜色, 结束颜色]
                            //     colors: [
                            //       Color.fromRGBO(216, 125, 143, 1.0),
                            //       Color.fromRGBO(208, 74, 74, 1.0),
                            //     ]),
                            color: Color.fromRGBO(238, 102, 102, 1),
                            borderRadius:
                            BorderRadius.all(Radius.circular(8.0.r))),
                        padding: EdgeInsets.fromLTRB(
                            0, Styles.spacing16, 0, Styles.spacing16),
                        margin: EdgeInsets.fromLTRB(
                            Styles.spacing8, 0, Styles.spacing8, 0),
                        child: Column(
                          children: [
                            Container(
                              child: Text(
                                '退货量',
                                style: TextStyle(
                                    color: Styles.ShareWhite,
                                    fontSize: Styles.NormalFont),
                              ),
                            ),
                            Container(
                              margin: EdgeInsets.only(top: Styles.spacing16),
                              padding: EdgeInsets.fromLTRB(
                                  0, Styles.spacing8, 0, Styles.spacing8),
                              child: Text(
                                '${cardInfo['returnVolume']}m³',
                                style: TextStyle(
                                    color: Styles.ShareWhite,
                                    fontSize: Styles.MiddleFont17),
                              ),
                            ),
                            Container(
                              padding: EdgeInsets.fromLTRB(0, 0, 0, 0),
                              child: Text(
                                '${cardInfo['returnQuantity']}片',
                                style: TextStyle(
                                    color: Styles.ShareWhite,
                                    fontSize: Styles.NormalFont),
                              ),
                            ),
                          ],
                        ),
                      )),
                ],
              ),
            ),
            Container(
              alignment: Alignment.center,
              child: Column(
                children: [
                  Container(
                    margin: EdgeInsets.only(top: Styles.spacing8),
                    color: Colors.white,
                    child: CustomRadio(
                      selectList: [
                        SelectItems(label: '方量(m³)',value: '1'),
                        SelectItems(label: '数量(片)',value: '2')
                      ],
                      selectCallback: (item) {
                        this.setState(() {
                          selectType = item.value;
                        });
                      },
                      title: '',
                    ),
                  ),
                  Container(
                    child: Stack(
                      children: [
                        Echarts(
                          onLoad: (value) {
                            LogUtil.d(value);
                            this.setState(() {
                              chartLoading = false;
                            });
                          },
                          option: '''
                    {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow',
            label: {
              show: true
            }
          }
        },
        calculable: true,
        legend: {
          data: ['完成量', '入库量', '发货量','退货量'],
          itemGap: 5
        },
        grid: {
          bottom:'20%',
          left: '1%',
          right: '8%',
          containLabel: true,
        },
        xAxis: [
          {
            type: 'category',
            data: ${this.charts.map((e){
                            return json.encode(e['everyDate']);
                          }).toList()},
                        axisLabel: {
              interval: ${currentStatus==3?1:0},
              
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: ${json.encode(selectType=='1'?'方量':'数量')},
           
            axisLabel: {
              formatter: function (a) {
                a = +a
                return isFinite(a) ? echarts.format.addCommas(+a) : ''
              }
            }
          }
        ],
        dataZoom: [
          {
            show: true,
            start: 0,
            end: 100,
          }
        ],
        series: [
          {
            name: '完成量',
            type: 'bar',
            data: ${this.charts.map((e){
                            return selectType=='1'?e['successVolume']:e['successQuantity'];
                          }).toList()}
          },
          {
            name: '入库量',
            type: 'bar',
            data: ${this.charts.map((e){
                            return selectType=='1'?e['warehouseVolume']:e['warehouseQuantity'];
                          }).toList()}
          },
          {
            name: '发货量',
            type: 'bar',
            data: ${this.charts.map((e){
                            return selectType=='1'?e['transportVolume']:e['transportQuantity'];
                          }).toList()}
          },
          {
            name: '退货量',
            type: 'bar',
            data: ${this.charts.map((e){
                            return selectType=='1'?e['returnVolume']:e['returnQuantity'];
                          }).toList()}
          }
        ]
      }
                  ''',
                          extraScript: '''
                    chart.on('click', (params) => {
                      if(params.componentType === 'series') {
                        Messager.postMessage(JSON.stringify({
                          type: 'select',
                          payload: params.dataIndex,
                        }));
                      }
                    });
                    chart.resize({width:${MediaQuery.of(context).size.width},height:300});
                  ''',
                          onMessage: (String message) {
                            LogUtil.d(message);
                            // Map<String, Object> messageAction = jsonDecode(message);
                            // print(messageAction);
                            // if (messageAction['type'] == 'select') {
                            //   final item = _data1[messageAction['payload']];
                            //   _scaffoldKey.currentState.showSnackBar(
                            //     SnackBar(
                            //       content: Text(item['name'].toString() + ': ' + item['value']),
                            //       duration: Duration(seconds: 2),
                            //     ));
                            // }
                          },
                        ),
                        chartLoading
                            ? Container(
                          alignment: Alignment.center,
                          child: CircularProgressIndicator(),
                        )
                            : Container()
                      ],
                    ),
                    width: 1.sw,
                    height: 400.h,
                  ),
                ],
              ),
            )
          ],
        ),
      ),
    );
  }
}
